package com.severez.bluetoothcontroller;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.severez.bluetoothcontroller.adapter.LeDeviceListAdapter;
import com.severez.bluetoothcontroller.ble.BLEListeners.OnConnectedListener;
import com.severez.bluetoothcontroller.ble.BLEListeners.OnServiceDiscoveredListener;
import com.severez.bluetoothcontroller.ble.BluetoothLeClass;
import com.severez.bluetoothcontroller.utils.MyDialogs;

public class ScaningActivity extends Activity {
    private final static String TAG = ScaningActivity.class.getSimpleName();

    private LeDeviceListAdapter mLeDeviceListAdapter;
    /** 搜索BLE终端 */
    private BluetoothAdapter mBluetoothAdapter;
    /** 读写BLE终端 */
    private BluetoothLeClass mBLE;
    private boolean mScanning;
    private static final long SCAN_PERIOD = 10000;

    private TextView tv_ScaningHint;
    private ListView lv_ScaningResult;
    private ProgressBar pBar_ScaningBar;
    private Button btn_reScan;

    private ProgressDialog pDialog;

    boolean alreadyTimeout = false;

    private Handler mHandler = new Handler() {
	public void handleMessage(Message msg) {
	    super.handleMessage(msg);
	    pDialog.dismiss();
	    if (msg.what == 0) {
		mHandler.removeCallbacksAndMessages(null);
		ScaningActivity.this.finish();
	    } else {
		alreadyTimeout = true;
		mHandler.removeCallbacksAndMessages(null);
		MyDialogs.getAlertDialog(ScaningActivity.this, "通知", "配对超时，请重试").setPositiveButton("确定", null).setCancelable(false).show();
	    }

	}
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	// TODO Auto-generated method stub
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_scaning);
	if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
	    Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
	    finish();
	}
	final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
	mBluetoothAdapter = bluetoothManager.getAdapter();

	// Checks if Bluetooth is supported on the device.
	if (mBluetoothAdapter == null) {
	    Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
	    finish();
	    return;
	}
	// 开启蓝牙
	mBluetoothAdapter.enable();
	mBLE = BluetoothLeClass.getInstance(this);
	if (!mBLE.initialize()) {
	    Log.e(TAG, "Unable to initialize Bluetooth");
	    finish();
	}

	mBLE.setOnConnectListener(onConnectedListener);
	mBLE.setOnServiceDiscoverListener(mOnServiceDiscover);
	// 收到BLE终端数据交互的事件
	mBLE.setOnDataAvailableListener(null);

	findViews();
    }

    private void findViews() {
	pBar_ScaningBar = (ProgressBar) findViewById(R.id.pbar_scaning);
	tv_ScaningHint = (TextView) findViewById(R.id.tv_scaninghint);
	lv_ScaningResult = (ListView) findViewById(R.id.lv_scaningresult);
	btn_reScan = (Button) findViewById(R.id.btn_rescan);

	lv_ScaningResult.setOnItemClickListener(new OnItemClickListener() {
	    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

		final BluetoothDevice device = mLeDeviceListAdapter.getDevice(position);
		if (device == null)
		    return;
		if (mScanning) {
		    mBluetoothAdapter.stopLeScan(mLeScanCallback);
		    mScanning = false;
		}
		pDialog = MyDialogs.getProgressDialog(ScaningActivity.this, R.string.connecting);
		pDialog.show();
		alreadyTimeout = false;
		mBLE.connect(device.getAddress());
		mHandler.sendEmptyMessageDelayed(1, 10000);
	    }
	});

	btn_reScan.setOnClickListener(new OnClickListener() {
	    public void onClick(View v) {
		if (mScanning) {
		    mBluetoothAdapter.stopLeScan(mLeScanCallback);
		    mScanning = false;
		}
		pBar_ScaningBar.setVisibility(View.VISIBLE);
		tv_ScaningHint.setText(R.string.scaning);
		mLeDeviceListAdapter.clear();
		scanLeDevice(true);
	    }
	});
    }

    protected void onResume() {
	super.onResume();
	// Initializes list view adapter.
	mLeDeviceListAdapter = new LeDeviceListAdapter(this);
	lv_ScaningResult.setAdapter(mLeDeviceListAdapter);
	scanLeDevice(true);
    }

    @Override
    protected void onPause() {
	super.onPause();
	scanLeDevice(false);
    }

    @Override
    protected void onStop() {
	super.onStop();
	if (mScanning) {
	    mBluetoothAdapter.stopLeScan(mLeScanCallback);
	    mScanning = false;
	}
    }

    private void scanLeDevice(final boolean enable) {
	if (enable) {
	    // Stops scanning after a pre-defined scan period.
	    mHandler.postDelayed(new Runnable() {
		@Override
		public void run() {
		    mScanning = false;
		    mBluetoothAdapter.stopLeScan(mLeScanCallback);
		    tv_ScaningHint.setText(R.string.scaning_done);
		    pBar_ScaningBar.setVisibility(View.GONE);
		}
	    }, SCAN_PERIOD);
	    Log.i(TAG, "--------------scaning-------------");
	    mScanning = true;
	    mBluetoothAdapter.startLeScan(mLeScanCallback);
	} else {
	    mScanning = false;
	    mBluetoothAdapter.stopLeScan(mLeScanCallback);
	}
    }

    // Device scan callback.
    private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {

	@Override
	public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
	    runOnUiThread(new Runnable() {
		@Override
		public void run() {
		    mLeDeviceListAdapter.addDevice(device);
		    Log.i(TAG, "device---->" + device);
		    mLeDeviceListAdapter.notifyDataSetChanged();
		}
	    });
	}
    };

    private OnConnectedListener onConnectedListener = new OnConnectedListener() {
	public void onConnected(BluetoothGatt gatt) {
	    // TODO Auto-generated method stub
	    Log.e(TAG, "-----------------onConnected----------------------");
	}
    };

    private OnServiceDiscoveredListener mOnServiceDiscover = new OnServiceDiscoveredListener() {

	@Override
	public void onServiceDiscovered(BluetoothGatt gatt) {
	    Log.e(TAG, "-----------------onServiceDiscoved----------------------");
	    if (!alreadyTimeout)
		mHandler.sendEmptyMessage(0);
	}
    };

}
